#include "communicator.h"

#include <QtDBus>

namespace Tubox {

Communicator::Communicator() throw(CommunicatorError) : iface(0) {
	if (!QDBusConnection::sessionBus().isConnected()) {
		throw CommunicatorError("Cannot connect to the D-Bus session bus.");
	}
	iface = new QDBusInterface("com.tubox.Daemon.Comm", "/", "", QDBusConnection::sessionBus());
	if (!iface->isValid()) {
		delete iface;
		throw CommunicatorError(string("Cannot create a DBus Interface.") + QDBusConnection::sessionBus().lastError().message().toStdString());
	}
}

Communicator::~Communicator() {
	if(iface) delete iface;
}

void Communicator::fileDownloaded(const File& file) throw(CommunicatorError) {
	QString message = "fileDownloaded";
	QDBusReply<QString> reply = iface->call(message, file.getFullPath());
	if (!reply.isValid()) {
		 throw CommunicatorError(string("Could not call a valid slot.") + reply.error().message().toStdString(), message);
	}
}

void Communicator::fileCreated(const File& file) throw(CommunicatorError) {
	QString message = "fileCreated";
	QDBusReply<QString> reply = iface->call(message, file.getFullPath());
	if (!reply.isValid()) {
		 throw CommunicatorError("Could not call a valid slot.", message);
	}
}

void Communicator::fileUploaded(const File& file) throw(CommunicatorError) {
	QString message = "fileUploaded";
	QDBusReply<QString> reply = iface->call(message, file.getFullPath());
	if (!reply.isValid()) {
		 throw CommunicatorError("Could not call a valid slot.", message);
	}
}

void Communicator::fileRenamed(const File& oldFile, const File& newFile) throw(CommunicatorError) {
QString message = "fileRenamed";
	QDBusReply<QString> reply = iface->call(message, oldFile.getFullPath(), newFile.getFullPath());
	if (!reply.isValid()) {
		 throw CommunicatorError("Could not call a valid slot", message);
	}
}

void Communicator::folderCreated(const Folder& folder) throw(CommunicatorError) {
	QString message = "folderCreated";
	QDBusReply<QString> reply = iface->call(message, folder.getFullPath());
	if (!reply.isValid()) {
		 throw CommunicatorError("Could not call a valid slot.", message);
	}
}

void Communicator::folderRenamed(const Folder& oldFolder, const Folder& newFolder) throw(CommunicatorError) {
	QString message = "folderRenamed";
	QDBusReply<QString> reply = iface->call(message, oldFolder.getFullPath(), newFolder.getFullPath());
	if (!reply.isValid()) {
		 throw CommunicatorError("Could not call a valid slot", message);
	}
}

}

